package p.ithorns.framework.feign.common;

import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import p.ithorns.framework.core.model.Result;

/**
 * BaseResponseBodyAdvice
 * TODO ithorns
 *
 * @author Ht.L
 * @date 2024-03-27 15:38
 * @since 1.0.0
 */
public class BaseResponseBodyAdvice implements ResponseBodyAdvice {

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return false;
    }

    @Override
    public Object beforeBodyWrite(Object body,
                                  MethodParameter returnType,
                                  MediaType selectedContentType,
                                  Class selectedConverterType,
                                  ServerHttpRequest request,
                                  ServerHttpResponse response) {
        // Feign请求时通过拦截器设置请求头，如果是Feign请求则直接返回实体对象
        if (isFeignCall(request)) {
            return body;
        }

        // 如果结果就是包装对象
        if(body instanceof Result){
            return body;
        }

        return Result.succeedWith(body);
    }

    private boolean isFeignCall(ServerHttpRequest request) {
        return request.getHeaders().containsKey(FeignConfig.REQUEST_ID);
    }

}